package io.gitee.itxinmeng.encrypt.spring.boot.db;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Map;

/**
 * @author mx
 */
public class AppAuthRepository {
    private static final String QUERY_SQL = "select app_key as appKey,app_secret as appSecret from {} where app_key = ? and status = 1 limit 1";
    private JdbcTemplate jdbcTemplate;
    private String tableName;

    public AppAuthRepository(JdbcTemplate jdbcTemplate,String tableName){
        this.jdbcTemplate = jdbcTemplate;
        this.tableName = tableName;
    }

    public void init() {
        jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS `"+tableName+"` (\n" +
                "  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',\n" +
                "  `app_key` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'key',\n" +
                "  `app_secret` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'secret',\n" +
                "  `app_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'type',\n" +
                "  `version` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'version',\n" +
                "  `status` tinyint DEFAULT NULL COMMENT 'status',\n" +
                "  PRIMARY KEY (`id`)\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='app auth';");
    }

    public AppAuth findAppAuthByAppKey(String appKey){
        Map<String, Object> appAuthMap = jdbcTemplate.queryForMap(StrUtil.format(QUERY_SQL,tableName),appKey);
        if(appAuthMap!=null){
            return JSONUtil.toBean(JSONUtil.parseObj(appAuthMap),AppAuth.class);
        }
        return null;
    }
}
